package oz.mano.online.netty.file_server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

public class HttpFileServer {
	
	private static final String DEFAULT_URL="/src/main/java/";
	
	public void run(final int port,final String url){
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		NioEventLoopGroup workGroup = new NioEventLoopGroup();

		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workGroup)
				.channel(NioServerSocketChannel.class)
				.childHandler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline pipeline = ch.pipeline();
					pipeline.addLast("http-decoder", new HttpRequestDecoder());
					pipeline.addLast("http-aggregator", new HttpObjectAggregator(65535));
					pipeline.addLast("http-encode", new HttpResponseEncoder());
					pipeline.addLast("http-chunked", new ChunkedWriteHandler());
					pipeline.addLast("fileServerHandler", new HttpFileServerHandler(url));
				}
			});
			
			String host ="127.0.0.1";
			ChannelFuture future = b.bind(host, port).sync();
			System.out.println("Http 文件目录服务器启动，网址是："+"http://localhost:"+port+url);
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
		
	}

	public static void main(String[] args) {
		
		int port = 8885;
		if(args.length>0){
			port = Integer.parseInt(args[0]);
		}
		String url =DEFAULT_URL;
		if(args.length>1){
			url = args[1];
		}
		new HttpFileServer().run(port, url);

	}

}
